<?php

namespace App\Http\Controllers\Api;

use App\Event;
use App\Http\Controllers\Controller;
use App\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class MessageController extends Controller
{
    public function show(Event $event){
        $messages = $event->messages;
        return $this->success($messages);
    }
    public function create(Request $request,Event $event){
        $validate = $this->validate($request,[
            'content'=>'required',
            'is_reply'=>'required|boolean'
        ]);

        if ($validate['is_reply'] == 1){
            $messages = $event->messages()->where('is_reply',0)->whereDate('created_datetime','<=',Carbon::now())->get();
            if (!empty($messages)){
                $messages->each(function ($item){
                    $item->reply_status = 1;
                    $item->save();
                });
            }
        }

        $message = new Message($validate);
        $message->event_id = $event->id;
        $message->created_datetime = Carbon::now();
        $message->save();

        return $this->success($message);
    }
}
